import type { ECharts } from 'echarts'
import type { PieData } from './index'

export const setPieChartOptions = (chart: ECharts, data: PieData[]) => {
  const total = data.reduce((pre, cur) => (pre += cur.value), 0)

  chart.setOption({
    tooltip: {
      trigger: 'item'
    },

    legend: {
      orient: 'vertical',
      left: 'right',
      align: 'left',
      y: 'center',
      itemGap: 10, // 图例每一项之间的间隔
      formatter: function (name: string) {
        const item = data.find(item => item.name === name)
        const rate = Number((item!.value / total) * 100).toFixed(2)
        const arr = ['{a|' + name + '}', '{b|' + '占比: ' + rate + '}']
        return arr.join('  ')
      },
      textStyle: {
        // 添加
        padding: [8, 0, 0, 0],
        rich: {
          a: {
            width: 40
          },
          b: {
            width: 70
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        data: data,
        // radius: ['90%'],
        center: ['20%', '50%'],
        label: {
          show: true,
          position: 'inside', // 标签显示在扇区内
          formatter(params: any) {
            if (params.percent === 0) {
              params.percent = ''
              return params.percent
            } else {
              return params.percent + '%'
            }
          }
        }
      }
    ]
  })
}

export const setBarChartOptions = (chart: ECharts, xData: number[], seriesData: number[]) => {
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    grid: {
      top: '40px',
      left: '30px',
      bottom: '30px',
      right: '50px'
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        fontSize: 11,
        formatter(v: number) {
          return `最长连续${v}月`
        }
      },
      data: xData
    },
    yAxis: {
      type: 'value',
      minInterval: 1 // 设置最小刻度间隔
    },
    series: [
      {
        type: 'bar',
        barWidth: 40,
        data: seriesData,
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  })
}
